package com.yimi.yinhepda.views.stockCheck_module;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

import com.pda.ym.entity.response.NoDataResponse;
import com.yimi.yinhepda.R;
import com.yimi.yinhepda.adapter.CheckScanListAdapter;
import com.yimi.yinhepda.adapter.SpinnerAdapter;
import com.pda.ym.callbacks.UICallBack;
import com.yimi.yinhepda.db.dao.CheckScanTableDao;
import com.yimi.yinhepda.db.table.CheckScanTable;
import com.yimi.yinhepda.entity.request.CheckScanRequest;
import com.yimi.yinhepda.entity.request.CheckUploadRequest;
import com.yimi.yinhepda.entity.request.QueryWaybillByChildNoRequest;
import com.yimi.yinhepda.entity.response.CheckScanTaskResponse;
import com.yimi.yinhepda.entity.response.QueryRetentionDictResponse;
import com.yimi.yinhepda.entity.response.QueryStorageAreaResponse;
import com.yimi.yinhepda.entity.response.QueryWaybillByChildNoResponse;
import com.yimi.yinhepda.entity.response.WaybillInfo;
import com.yimi.yinhepda.event.CountEvent;
import com.pda.ym.net.NetRequest;
import com.yimi.yinhepda.utils.Common;
import com.pda.ym.utils.Constants;
import com.yimi.yinhepda.utils.IntentUtils;
import com.pda.uce.commom.util.MyDialog;
import com.pda.ym.utils.SharedPreferUtil;
import com.pda.ym.utils.SoundVibratorManager;
import com.pda.ym.utils.StringUtils;
import com.yimi.yinhepda.base.BaseInitActivity;

import org.greenrobot.eventbus.EventBus;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;

/**
 * 盘点具体单号的扫描界面
 *
 * @author tianjin
 */
public class CheckScanActivity extends BaseInitActivity implements AdapterView.OnItemSelectedListener, View.OnTouchListener {

    private static final String TAG = "CheckScanActivity";
    /**
     * 标题栏左边
     */
    @Bind(R.id.title)
    TextView mTvTitle;
    /**
     * 标题栏中间
     */
    @Bind(R.id.num)
    TextView mTvNum;
    @Bind(R.id.next_station)
    TextView mNextStation;
    @Bind(R.id.check_task_listview)
    ListView mListView;
    /**
     * 库存票
     */
    @Bind(R.id.stock_piao)
    TextView mTvStockTicket;
    /**
     * 库存件
     */
    @Bind(R.id.stock_jian)
    TextView mTvStockPieces;
    /**
     * 扫描票
     */
    @Bind(R.id.scaned_piao)
    TextView mTvScannedTicket;
    /**
     * 扫描件
     */
    @Bind(R.id.scaned_jian)
    TextView mTvScanedPieces;
    /**
     * 滞留原因
     */
    @Bind(R.id.sp_retention)
    Spinner mSpRetention;

    /**
     * 数据展示集合
     */
    private List<HashMap<String, Object>> resultDataList;
    /**
     * 当前操作条目
     */
    private List<HashMap<String, Object>> currentItem = new ArrayList<HashMap<String, Object>>();
    /**
     * 盘点单号
     */
    private String mStockNo;
    private String mStockArea;
    private String mStockCode;
    private CheckScanListAdapter mAdapter;
    /**
     * 运单号号的集合,全局的,手动添加，撤销都使用它, 但是注意释放
     */
    public static List<CheckScanTaskResponse.CheckScanEntity> mCheckScanList = new ArrayList<>();
    private CheckScanTableDao mCheckScanTableDao;
    /**
     * 总的未上传数量
     */
    private int totalNotUploadNum;
    /**
     * 滞留原因数据列表
     */
    private List<String> mRetentionList;
    /**
     * 滞留原因适配器
     */
    private SpinnerAdapter mRetentionAdapter;
    private boolean isSpinnerFirst = true;
    /**
     * 设置默认滞留原因
     */
    private String spinnerRetentionData = "";
    /**
     * 滞留原因map
     */
    private Map<String, String> retentionMap;

    @Override
    public String getPageName() {
        return getString(R.string.page_check_scan);
    }

    public CheckScanActivity() {
        super(true);
    }

    @Override
    public int getContentViewId() {
        return R.layout.activity_check_scan;
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        mTvTitle.setText(getString(R.string.check_scan_title));
        //盘点单号
        mStockNo = getIntent().getExtras().getString(IntentUtils.STOCK_NO);
        //库区
        mStockArea = getIntent().getExtras().getString(IntentUtils.STOCK_AREA);
        //库区编码
        mStockCode = getIntent().getExtras().getString("storageCode");
        //数据表
        mCheckScanTableDao = new CheckScanTableDao();
        //查询未上传数据
        totalNotUploadNum = mCheckScanTableDao.queryNotUploadDataNum();
        mTvNum.setText(totalNotUploadNum + "");
        //下一站？
        mNextStation.setText(mStockArea);
    }

    @Override
    public void initEvent() {
        mSpRetention.setOnTouchListener(this);
        mSpRetention.setOnItemSelectedListener(this);
        findViewById(R.id.check_scan_back).setOnClickListener(this);
        findViewById(R.id.check_scan_refresh).setOnClickListener(this);
        findViewById(R.id.check_scan_upload).setOnClickListener(this);
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                Bundle bundle = new Bundle();
                bundle.putString(IntentUtils.BUILD_WAYBILLNO, mCheckScanList.get(i).getWaybillNo());
                bundle.putString("stockNo", mStockNo);
                bundle.putSerializable("retentionList", (Serializable) mRetentionList);

                Intent intent = new Intent(CheckScanActivity.this, CheckWaybillDetailActivity.class);
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });
    }

    @Override
    public void initData() {
        mRetentionList = new ArrayList<>();
        //获取滞留原因
        requestGetRetention();

        loadData();
    }

    /**
     * 从数据字典中，获取滞留原因
     */
    private void requestGetRetention() {
        Map<String, String> params = new HashMap<>();
        //移库倒货数据字典字段
        params.put("params", "stock_taking_stranded");
        new NetRequest().setMethod(NetRequest.Method.GET)
                .setUrl(Constants.URL_QUERY_DICT_VALUE)
                .setParams(params)
                .setConnTimeOut(5 * 1000)
                .setResponsClazz(QueryRetentionDictResponse.class)
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        showToast(msg);
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        QueryRetentionDictResponse response = (QueryRetentionDictResponse) obj;
                        if (response.getData() != null) {
                            retentionMap = response.getData().getRetentionReason();
                            if (retentionMap != null) {
                                for (String key : retentionMap.keySet()) {
                                    String value = retentionMap.get(key);
                                    mRetentionList.add(value);
                                }
                            }
                        }
                        if (mRetentionList == null || mRetentionList.isEmpty()) {
                            mSpRetention.setPrompt("请先维护滞留原因");
                        } else {
                            mSpRetention.setPrompt("请选择滞留原因");
                        }
                        mRetentionAdapter = new SpinnerAdapter(CheckScanActivity.this, R.layout.simple_spinner_item, mRetentionList);
                        mSpRetention.setAdapter(mRetentionAdapter);
                    }
                });
    }

    /**
     * 获取网络数据
     */
    public void loadData() {
        setScannerEnabled(false);
        showPgDlg("正在加载...");

        new NetRequest().setMethod(NetRequest.Method.POST_STRING)
                .setResponsClazz(CheckScanTaskResponse.class)
                .setUrl(Constants.URL_CLEAR_SCAN)
                .setRequestObject(new CheckScanRequest(mStockNo))
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        showToast(msg);
                        SoundVibratorManager.playSound(2);
                        dismissPgDlg();
                        setScannerEnabled(true);
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        if (obj instanceof CheckScanTaskResponse) {
                            CheckScanTaskResponse response = (CheckScanTaskResponse) obj;
                            if (response.data == null || response.data.size() <= 0) {
                                showToast("当前盘点的货区没有库存！");
                                SoundVibratorManager.playSound(2);
                            } else {
                                /**
                                 * 获取到数据
                                 */
                                showDataDetail(response);
                                SoundVibratorManager.playSound(1);
                            }
                        }
                        dismissPgDlg();
                        setScannerEnabled(true);
                    }
                });
    }

    /**
     * 显示数据到列表
     */
    public void showDataDetail(CheckScanTaskResponse response) {
        //接口数据
        mCheckScanList = setProductType(response.getData());
        //查询本地子单数据，若不存在子单列表中，则将其插入
        for (CheckScanTaskResponse.CheckScanEntity checkScanEntity : mCheckScanList) {
            List<CheckScanTable> checkScanTables = mCheckScanTableDao.getWaybillNoData(mStockNo, checkScanEntity.getWaybillNo());
            if (checkScanTables == null) {
                continue;
            }
            for (CheckScanTable checkScanTable : checkScanTables) {
                if (!checkScanTable.getWaybillNo().equals(checkScanEntity.getWaybillNo())) {
                    //本地运单和列表中的运单不相等
                    continue;
                }
                boolean hasData = false;
                if (checkScanEntity.getStocktakingDiffreportInventoryList() != null) {
                    for (CheckScanTaskResponse.ChildInfo childInfo : checkScanEntity.getStocktakingDiffreportInventoryList()) {
                        if (checkScanTable.getWaybillChildNo().equals(childInfo.getWaybillChildNo())) {
                            hasData = true;
                            break;
                        }
                    }
                } else {
                    checkScanEntity.setStocktakingDiffreportInventoryList(new ArrayList<CheckScanTaskResponse.ChildInfo>());
                }
                if (!hasData) {
                    CheckScanTaskResponse.ChildInfo childInfo = new CheckScanTaskResponse.ChildInfo();
                    childInfo.setStockStatus(checkScanTable.getScanStatus());
                    childInfo.setWaybillChildNo(checkScanTable.getWaybillChildNo());
                    checkScanEntity.getStocktakingDiffreportInventoryList().add(childInfo);
                }
            }
        }

        //颜色排序
        Collections.sort(mCheckScanList);

        //列表
        mAdapter = new CheckScanListAdapter(this, mCheckScanList);
        mListView.setAdapter(mAdapter);

        //库存票，件
        mTvStockTicket.setText(response.getStockTicket(mCheckScanList) + "");
        mTvStockPieces.setText(response.getStockPieces(mCheckScanList) + "");

        //已扫描票，件
        mTvScannedTicket.setText(response.getTotalScannedTicket(mCheckScanList) + "");
        mTvScanedPieces.setText(response.getTotalScannedPiece(mCheckScanList) + "");
    }

    /**
     * 由于返回时，表示数据暂存了，
     * 那么再次进入页面判断对应接口数据，数据库中是否已经存在并且已经扫描
     * <p>
     * 如果提交成功，状态就变为1了，所以再次进入也不需要判断了
     */
    private void justResponseDataStatus() {
        if (mCheckScanList.size() <= 0) {
            return;
        }

        for (CheckScanTaskResponse.CheckScanEntity entity : mCheckScanList) {
            //主单
            String waybillNo = entity.getWaybillNo();
            //子单集合
            List<CheckScanTaskResponse.ChildInfo> childList = entity.getStocktakingDiffreportInventoryList();
            for (CheckScanTaskResponse.ChildInfo childItem : childList) {
                //子单
                String childWayBillNo = childItem.getWaybillChildNo();
                //查询数据库，是否已经扫描
                int status = mCheckScanTableDao.findChildWayBillNoStatus(mStockNo, waybillNo, childWayBillNo);
                if (status == 1) {
                    //数据库中已经扫描的，设置当前数据状态为已扫描
                    childItem.setStockStatus(1);
                }
            }
        }
    }

    /**
     * 扫描的回调
     */
    @Override
    protected void handleBarCode(String result) {
        super.handleBarCode(result);
        if (result == null) {
            SoundVibratorManager.playSound(2);
            showToast("运单号扫描失败");
        } else {
            doScan(result);
        }
    }

    /**
     * 巴枪扫描完成，返回处理条码，刷新列表，显示扫描数量
     *
     * @param result 扫描的子单
     */
    private void doScan(String result) {

        if (spinnerRetentionData == null || "".equals(spinnerRetentionData)) {
            showToast("请确认选择滞留原因！");
            SoundVibratorManager.playSound(2);
            return;
        }

        if (!StringUtils.isWaybillNo(result) && !StringUtils.isPackgeNo(result)) {
            SoundVibratorManager.playSound(2);
            showToast("单号或包号不规范!");
            return;
        }
        /** 条码在任务内*/
        if (mCheckScanList != null) {
            for (int i = 0; i < mCheckScanList.size(); i++) {
                CheckScanTaskResponse.CheckScanEntity currentItemInfo = mCheckScanList.get(i);
                //判断子单是不是以主单开始的,减少循环次数
                if (!result.startsWith(currentItemInfo.getWaybillNo())) {
                    continue;
                }
                //子单集合
                List<CheckScanTaskResponse.ChildInfo> childList = currentItemInfo.getStocktakingDiffreportInventoryList();
                CheckScanTaskResponse.ChildInfo tempChildInfo = null;
                if (childList == null) {
                    break;
                }
                //循环出单个子单
                for (CheckScanTaskResponse.ChildInfo childInfo : childList) {
                    String childWayBillNO = childInfo.getWaybillChildNo();
                    /** 扫描的子单发现在任务中*/
                    if (result.equals(childWayBillNO)) {
                        //设置滞留原因
                        childInfo.setColumn1(spinnerRetentionData);
                        tempChildInfo = childInfo;
                        break;
                    }
                }

                /**判断该子单号是否已打印，未打印给出提示，并且禁止扫描*/
                if (tempChildInfo != null) {
                    boolean isBePrint = isBePrintChileWayBill(currentItemInfo, tempChildInfo);
                    if (!isBePrint) {
                        return;
                    }
                }

                if (tempChildInfo == null) {
                    tempChildInfo = new CheckScanTaskResponse.ChildInfo();
                    tempChildInfo.setWaybillChildNo(result);
                    tempChildInfo.setStockStatus(0);
                    //设置滞留原因
                    tempChildInfo.setColumn1(spinnerRetentionData);
                    currentItemInfo.getStocktakingDiffreportInventoryList().add(tempChildInfo);
                }

                Integer status = tempChildInfo.getStockStatus();
                if (status == 1) {
                    SoundVibratorManager.playSound(2);
                    showToast("运单已扫描！");
                    return;
                } else {
                    /** 扫描数据插入到表中*/
                    if (insertScannedData(currentItemInfo, tempChildInfo.getWaybillChildNo()) < 0) {
                        SoundVibratorManager.playSound(2);
                        showToast("插入数据库失败!");
                        return;
                    }
                    //查询未上传数据
                    totalNotUploadNum = mCheckScanTableDao.queryNotUploadDataNum();
                    mTvNum.setText(totalNotUploadNum + "");
                    EventBus.getDefault().post(new CountEvent(totalNotUploadNum));

                    /** 设置该子单为已扫描的状态*/
                    tempChildInfo.setStockStatus(1);

                    /** 刷新增加的已扫描票和件*/
                    mTvScannedTicket.setText(CheckScanTaskResponse.getTotalScannedTicket(mCheckScanList) + "");
                    mTvScanedPieces.setText(CheckScanTaskResponse.getTotalScannedPiece(mCheckScanList) + "");
                    //上传数据
                    uploadData();
                }

                /** 更新当前行到第一行*/
                mCheckScanList.remove(i);
                mCheckScanList.add(0, currentItemInfo);
                /**排序按照颜色：红，白，黄，绿*/
                Collections.sort(mCheckScanList);
                if (mAdapter == null) {
                    //列表
                    mAdapter = new CheckScanListAdapter(this, mCheckScanList);
                }
                /** 刷新列表*/
                mAdapter.notifyDataSetChanged();
                return;
            }
        }

        //该条码不在配载单据内
        //查询库区
        queryStorageCode(result);
    }

    /**
     * 查询库区
     */
    private void queryStorageCode(final String result) {
        showPgDlg("查询库区中...");
        String temResult = result.substring(0, result.length() - 3);
        Map param = new HashMap(1);
        param.put("waybillNo", temResult);
        new NetRequest().setUrl(Constants.URL_GET_STORAGE_CODE)
                .setMethod(NetRequest.Method.GET)
                .setParams(param)
                .setResponsClazz(QueryStorageAreaResponse.class)
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        dismissPgDlg();
                        showToast(msg);
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        dismissPgDlg();
                        QueryStorageAreaResponse response = (QueryStorageAreaResponse) obj;
                        if (response != null) {
                            QueryStorageAreaResponse.Data data = response.getData();
                            if (data != null) {
                                if (data.getStorageCode() != null) {
                                    if (!data.getStorageCode().equals(mStockCode)) {
                                        //提示：非本库区货物，请挪至正确库区
                                        SoundVibratorManager.playSound(2);
                                        MyDialog.showAlertDialog(CheckScanActivity.this, "提示", "非本库区货物，请挪至正确库区\"" + data.getStorageCode() + "\"", "是");
                                    }
                                } else {
                                    //提示：该线路未找到对应库区，请维护库区
                                    SoundVibratorManager.playSound(2);
                                    MyDialog.showAlertDialog(CheckScanActivity.this, "提示", "该线路未找到对应库区，请维护库区", "是");

                                }
                            }
                        }
                        //子单下载主单
                        downloadWaybillNo(result);

                    }
                });
    }

    /**
     * 判断该子单号是否已打印，未打印给出提示，并且禁止扫描
     *
     * @param childBean 子单实体
     */
    private boolean isBePrintChileWayBill(CheckScanTaskResponse.CheckScanEntity checkScanEntity, CheckScanTaskResponse.ChildInfo childBean) {
        if (childBean.getBePrint() == null || childBean.getBePrint() == 2) {
            //字段为2或者空-已打印
            SoundVibratorManager.playSound(1);
            return true;
        } else if (childBean.getBePrint() == 1) {
            //1-未打印，禁止扫描
            //设置该标志，不返回扫描结果
//            MyDialog.setTag(1);
            MyDialog dialog = MyDialog.getInstance(this);
            dialog.setIcon(R.drawable.alert);
            dialog.setDialogType(MyDialog.DialogType.ALERT_DIALOG);
            dialog.setTitle("系统提示");
            dialog.setMessage("该票货发生目的站更改，请补打标签更换！");
            dialog.setPositiveClickListener( "确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    MyDialog.setNull();
                }
            });
            dialog.setCancelable(false);
            dialog.setCanceledOnTouchOutside(false);
            if (checkScanEntity.getScannedNum() == 0) {
                //扫描第一件做打断提示
                //设置该标志，不返回扫描结果
//                MyDialog.setTag(1);
                try {
                    dialog.show();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return true;
            }
        }
        return true;
    }

    /**
     * 子单下载主单
     */
    private void downloadWaybillNo(final String result) {
        setScannerEnabled(false);
        showPgDlg("正在子单下载主单...");
        //扫描数据上传完后  调完成任务
        QueryWaybillByChildNoRequest mQueryWaybillByChildNoRequest = new QueryWaybillByChildNoRequest();
        mQueryWaybillByChildNoRequest.setChildWaybillNo(result);

        Map<String, String> params = new HashMap<>();
        params.put("childWaybillNo", result);

        new NetRequest().setMethod(NetRequest.Method.GET)
                .setResponsClazz(QueryWaybillByChildNoResponse.class)
                .setUrl(Constants.URL_FORCE_SCAN)
                .setParams(params)
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        //开启扫描
                        setScannerEnabled(true);
                        dismissPgDlg();
                        SoundVibratorManager.playSound(2);
                        disableScan();
                        showForceScanErrorDialog(msg);
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        if (obj instanceof QueryWaybillByChildNoResponse) {
                            QueryWaybillByChildNoResponse response = (QueryWaybillByChildNoResponse) obj;
                            //盘点没有路由判断，相当于卸车
                            //合并数据到内存，并插入当前条码到数据库
                            merge(response.getData(), result);
                        }
                        //开启扫描
                        setScannerEnabled(true);
                        dismissPgDlg();
                    }
                });
    }

    /**
     * 合并数据到内存，并插入当前条码到数据库
     */
    private void merge(WaybillInfo data, String result) {
        //构建数据
        CheckScanTaskResponse.CheckScanEntity checkScanEntity = new CheckScanTaskResponse.CheckScanEntity();
        checkScanEntity.setWaybillNo(data.getWaybillNo() + "");
        checkScanEntity.setChargeableWeight(data.getChargeableWeight());
        checkScanEntity.setInventoryNum(data.getNowInventory());
        checkScanEntity.setPackingSpecification(data.getPackingSpecification());
        checkScanEntity.setQuantity(data.getQuantity());
        checkScanEntity.setRealWeight(data.getRealWeight());
        checkScanEntity.setVolume(data.getVolume());
        checkScanEntity.setRemark("2");

        List<CheckScanTaskResponse.ChildInfo> childList = new ArrayList<CheckScanTaskResponse.ChildInfo>();
        for (int i = 0; i < data.getQuantity(); i++) {
            String childWaybillNo = data.getWaybillNo() + String.format("%03d", i + 1);
            CheckScanTaskResponse.ChildInfo mChildInfo = new CheckScanTaskResponse.ChildInfo();
            if (result.equals(childWaybillNo)) {
                mChildInfo.setStockStatus(1);
                //设置滞留原因
                mChildInfo.setColumn1(spinnerRetentionData);
            } else {
                mChildInfo.setStockStatus(0);
            }
            mChildInfo.setWaybillChildNo(childWaybillNo);
            childList.add(mChildInfo);
        }
        //子单集合加入到运单对象中
        checkScanEntity.setStocktakingDiffreportInventoryList(childList);

        //扫描的子单插入到数据库
        if (insertScannedData(checkScanEntity, result) < 0) {
            showToast("插入数据失败!");
            return;
        }

        //未上传数据
        totalNotUploadNum++;
        mTvNum.setText(totalNotUploadNum + "");
        EventBus.getDefault().post(new CountEvent(totalNotUploadNum));

        if (mCheckScanList == null) {
            mCheckScanList = new ArrayList<>();
        }
        Collections.sort(mCheckScanList);
        mCheckScanList.add(0, checkScanEntity);
        if (mAdapter == null) {
            mAdapter = new CheckScanListAdapter(this, mCheckScanList);
            mListView.setAdapter(mAdapter);
        } else {
            mAdapter.setmDataList(mCheckScanList);
        }
        mAdapter.notifyDataSetChanged();

        /** 刷新增加的已扫描票和件*/
        mTvScannedTicket.setText(CheckScanTaskResponse.getTotalScannedTicket(mCheckScanList) + "");
        mTvScanedPieces.setText(CheckScanTaskResponse.getTotalScannedPiece(mCheckScanList) + "");

        //上传数据
        uploadData();
    }

    /**
     * 插入已经扫描的数据到表中
     *
     * @param currentItemInfo 当前运单号的相关信息
     * @param waybillChildNo  当前子单的相关信息
     */
    private int insertScannedData(CheckScanTaskResponse.CheckScanEntity currentItemInfo, String waybillChildNo) {
        CheckScanTable checkScanTable = new CheckScanTable();
        checkScanTable.setStockNo(mStockNo);
        checkScanTable.setWaybillNo(currentItemInfo.getWaybillNo());
        checkScanTable.setInputTime(Constants.GetScanTime());
        checkScanTable.setOperTime(Constants.GetSysTime());
        //1扫描输入，2手动输入
        checkScanTable.setInputType(1);
        checkScanTable.setInputUser(SharedPreferUtil.getInstance().getValue(Common.USER_CODE));
        checkScanTable.setWaybillChildNo(waybillChildNo);
        //已扫描
        checkScanTable.setScanStatus(1);
        //未上传
        checkScanTable.setIsUpload(0);
        //滞留原因
        checkScanTable.setRetention(spinnerRetentionData);
        int result = 0;
        try {
            boolean exitData = mCheckScanTableDao.exitChildWaybillNoData(mStockNo, waybillChildNo);
            if (exitData) {
                result = mCheckScanTableDao.update(checkScanTable);
            } else {
                result = mCheckScanTableDao.insert(checkScanTable);
            }
        } catch (Exception e) {
            e.printStackTrace();
            result = -1;
        }
        return result;
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            //返回按钮，任务暂存集
            case R.id.check_scan_back:
                finish();
                break;
            case R.id.check_scan_refresh:
                loadData();
                break;
            case R.id.check_scan_upload:
                //if (mCheckScanList == null || mCheckScanList.size() <= 0) {
                //  showToast(getString(R.string.tmp_no_data));
                //  return;
                //}
                //if (!isScanBill()) {
                //  showToast(getString(R.string.no_scan_num));
                //  return;
                //}
                MyDialog myDialog = new MyDialog(CheckScanActivity.this);
                myDialog.setIcon(R.drawable.alert);
                myDialog.setMessage("提交后将完成盘点，是否提交？");
                myDialog.setPositiveClickListener( Constants.confirmMsg, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //完成扫描
                        completeTask();
                        dialog.dismiss();
                    }
                });
                myDialog.setNegativeClickListener(R.drawable.btn_cancel_selector, Constants.cancelMsg, null);
                myDialog.show();
                break;
            default:
                break;
        }
    }

    /**
     * 判断是否重复扫描
     */
    private boolean isScanBill() {
        for (int i = 0; i < mCheckScanList.size(); i++) {
            CheckScanTaskResponse.CheckScanEntity currentItemInfo = mCheckScanList.get(i);
            //子单集合
            List<CheckScanTaskResponse.ChildInfo> childList = currentItemInfo.getStocktakingDiffreportInventoryList();
            if (childList == null) {
                return false;
            }
            //循环出单个子单
            for (CheckScanTaskResponse.ChildInfo childInfo : childList) {
                String childWayBillNO = childInfo.getWaybillChildNo();
                /** 扫描的单子发现在任务中*/
                Integer status = childInfo.getStockStatus();
                if (status == 1) {
                    return true;
                }
            }
        }
        return false;
    }

    boolean isUploading = false;

    /**
     * 扫描完成, ,提交数据，到接口
     * <p>
     * 这里是查出所有，一起上传
     */
    public void uploadData() {
        setScannerEnabled(false);
        if (isUploading) {
            Log.d(TAG, "uploadData: 正在上传数据中...");
            return;
        }
        showPgDlg("正在提交...");
        //控制正在上传
        isUploading = true;

        //获取未上传的数据，然后判断
        final List<CheckScanTable> unUploadList = mCheckScanTableDao.getUnUploadDataList();
        if (unUploadList == null || unUploadList.size() <= 0) {
            isUploading = false;
            dismissPgDlg();
            setScannerEnabled(true);
            return;
        }

        //上传的json对象
        CheckUploadRequest checkUploadRequestList = getBuildUploadData(unUploadList);

        new NetRequest().setMethod(NetRequest.Method.POST_STRING)
                .setResponsClazz(NoDataResponse.class)
                .setUrl(Constants.URL_CLEAR_UPLOAD_SCAN)
                .setRequestObject(checkUploadRequestList)
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        isUploading = false;
                        dismissPgDlg();
                        setScannerEnabled(true);
                        showToast(msg);
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        if (obj instanceof NoDataResponse) {
                            Log.d(TAG, "onResponse: 上传成功!");

                            //更新未上传字段为已上传
                            for (CheckScanTable itemTable : unUploadList) {
                                itemTable.setIsUpload(1);
                                mCheckScanTableDao.updataItem(itemTable);
                            }

                            //减少未上传是数量
                            totalNotUploadNum = totalNotUploadNum - unUploadList.size();
                            if (totalNotUploadNum < 0) {
                                totalNotUploadNum = 0;
                            }
                            mTvNum.setText(totalNotUploadNum + "");
                            EventBus.getDefault().post(new CountEvent(totalNotUploadNum));
                        }

                        //状态
                        isUploading = false;
                        dismissPgDlg();
                        setScannerEnabled(true);
                    }
                });
    }

    /**
     * 上传数据的对象
     */
    private CheckUploadRequest getBuildUploadData(List<CheckScanTable> unUploadList) {

        CheckUploadRequest checkUploadRequest = new CheckUploadRequest();
        //集合
        List<CheckUploadRequest.CheckUploadEntity> mUpladList = new ArrayList<>();
        for (CheckScanTable itemTable : unUploadList) {
            //上传的具体子单信息的对象
            CheckUploadRequest.CheckUploadEntity checkUploadEntity = new CheckUploadRequest.CheckUploadEntity();
            checkUploadEntity.setStockNo(itemTable.getStockNo());
            checkUploadEntity.setWaybillNo(itemTable.getWaybillNo());
            checkUploadEntity.setWaybillChildNo(itemTable.getWaybillChildNo());
            checkUploadEntity.setInputTime(itemTable.getInputTime());
            checkUploadEntity.setInputType(itemTable.getInputType());
            checkUploadEntity.setInputUser(itemTable.getInputUser());
            //设置滞留原因
            checkUploadEntity.setNote(itemTable.getRetention());
            //加入对象的集合中
            mUpladList.add(checkUploadEntity);
        }
        //list放到对象中
        checkUploadRequest.setStockTakingDetailsVoList(mUpladList);
        return checkUploadRequest;
    }

    /**
     * 点击提交, 如果有未提交的，先上传数据接口，再提交完成接口
     */
    private void completeTask() {
        final List<CheckScanTable> unUploadList = mCheckScanTableDao.getUnUploadDataList();
        if (unUploadList == null || unUploadList.size() <= 0) {
            //数据已经全部上传，就可以提交完成了
            lastCompleteUpload();
            return;
        }

        //关闭扫描
        setScannerEnabled(false);
        showPgDlg("正在提交扫描数据...");

        //最后去上传一次
        CheckUploadRequest checkUploadRequestList = getBuildUploadData(unUploadList);

        new NetRequest().setMethod(NetRequest.Method.POST_STRING)
                .setResponsClazz(NoDataResponse.class)
                .setUrl(Constants.URL_CLEAR_UPLOAD_SCAN)
                .setRequestObject(checkUploadRequestList)
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        showToast(msg);
                        SoundVibratorManager.playSound(2);
                        dismissPgDlg();
                        setScannerEnabled(true);
                    }

                    @Override
                    public void onSuccess(Object obj) {

                        //更新未上传字段为已上传
                        for (CheckScanTable itemTable : unUploadList) {
                            itemTable.setIsUpload(1);
                            mCheckScanTableDao.updataItem(itemTable);
                        }

                        //减少未上传是数量
                        totalNotUploadNum = totalNotUploadNum - unUploadList.size();
                        if (totalNotUploadNum < 0) {
                            totalNotUploadNum = 0;
                        }
                        mTvNum.setText(totalNotUploadNum + "");
                        EventBus.getDefault().post(new CountEvent(totalNotUploadNum));

                        dismissPgDlg();
                        setScannerEnabled(true);

                        //最后调用完成接口
                        lastCompleteUpload();
                    }
                });
    }

    /**
     * 访问完成的接口
     */
    private void lastCompleteUpload() {
        //关闭扫描
        setScannerEnabled(false);
        showPgDlg("正在提交任务...");

        new NetRequest().setMethod(NetRequest.Method.POST_STRING)
                .setResponsClazz(NoDataResponse.class)
                .setUrl(Constants.URL_CLEAR_SCAN_COMPLETE)
                .setRequestObject(new CheckScanRequest(mStockNo))
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        showToast(msg);
                        SoundVibratorManager.playSound(2);
                        dismissPgDlg();
                        setScannerEnabled(true);
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        showToast("盘点完成！");
                        SoundVibratorManager.playSound(1);
                        dismissPgDlg();
                        setScannerEnabled(true);

                        //结束
                        mCheckScanList = null;
                        finish();
                    }
                });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //静态数据清掉
        if (mCheckScanList != null) {
            mCheckScanList.clear();
            mCheckScanList = null;
        }
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        if (isSpinnerFirst) {
            spinnerRetentionData = "";
            //第一次不显示默认的第一项
            view.setVisibility(View.INVISIBLE);
            isSpinnerFirst = false;
        } else {
            String value = mRetentionList.get(position);
            for (Map.Entry<String, String> entry : retentionMap.entrySet()) {
                if (value.equals(entry.getValue())) {
                    spinnerRetentionData = entry.getKey() + "";
                    view.setVisibility(View.VISIBLE);
                    break;
                }
            }
        }
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        //解决spinner的item点击事件只能点击一次
        try {
            Class<?> clazz = AdapterView.class;
            Field field = clazz.getDeclaredField("mOldSelectedPosition");
            field.setAccessible(true);
            field.setInt(mSpRetention, AdapterView.INVALID_POSITION);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 设置二级排序的产品类型
     */
    private List<CheckScanTaskResponse.CheckScanEntity> setProductType(List<CheckScanTaskResponse.CheckScanEntity> list) {
        for (CheckScanTaskResponse.CheckScanEntity item : list) {
            item.setSecondSort(Common.setSecondType(item.getProductTypeSelect(), item.getEffectiveType(), item.getWaybillNo()));
        }
        return list;
    }
}
